package es.deusto.engineering.is.kbs.util;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;

public final class KnowledgeBaseLoader {
	
	/**
	 * Load a Knowledge Base from a DRL file.
	 * @param drlFile String with the name of the DRL file
	 * @return KnowledgeBase containing the rules from the DRL file
	 */
	public static KnowledgeBase loadKnowledgeBase(String drlFile) {
		KnowledgeBase kbase = null;
		
		try {		
			KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
			kbuilder.add(ResourceFactory.newClassPathResource(drlFile), ResourceType.DRL);
		
			KnowledgeBuilderErrors errors = kbuilder.getErrors();		
			if (errors.size() > 0) {			
				System.err.println("* Errors were found during the rules file loading: ");
				for (KnowledgeBuilderError error: errors) {
					System.err.println("  - " + error);
				}			
			}
			
			kbase = KnowledgeBaseFactory.newKnowledgeBase();
			kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());		
		} catch (Exception ex) {
			System.err.println("%[loadKnowledgeBase() - Error]: " + ex.getMessage());
			ex.printStackTrace(System.err);
		}
		
		return kbase;
	}
}